package com.copa.gamestore.module.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.copa.gamestore.module.user.domain.dto.UserDto;
import com.copa.gamestore.module.user.domain.User;
import com.copa.gamestore.module.user.mapper.UserMapper;
import com.copa.gamestore.module.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.ValidationException;
import java.util.Optional;

/**
 * @author copa
 * @createDate 2022-09-22 11:16
 * @function
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("username", username);
        return Optional.ofNullable(userMapper.selectOne(wrapper))
                .orElseThrow(() -> new UsernameNotFoundException("用户" + username + "不存在"));
    }

    @Override
    public User register(UserDto userDto) {
        // 永远不要相信前端传过来的鬼话~不可能有id哒~
        userDto.setId(null);
        repeatUser(userDto);
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        if (userMapper.insert(user) <= 0) {
            throw new RuntimeException();
        }
        return user;
    }

    @Override
    public void put(UserDto userDto) {
        // 只能修改信息，不能修改密码，若想改密码~嘿嘿嘿~
        userDto.setPassword(null);
        // 不允许改用户名，用户名是该系统的唯一标识
        userDto.setUsername(null);
        //repeatUserUpdate(userDto);
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        if (userMapper.updateById(user) <= 0) {
            throw new RuntimeException();
        }
    }

    @Override
    public void resetPassword(String username) {
        // 重置写死123456（只是为了演示）
        User user = Optional.ofNullable(userMapper.selectOne(
                        new QueryWrapper<User>().eq("username", username)))
                .orElseThrow(() -> new ValidationException("非法操作~"));
        user.setPassword(passwordEncoder.encode("123456"));
        if (userMapper.updateById(user) <= 0) {
            throw new RuntimeException();
        }
    }

    @Override
    public User findById(Long id) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("id", id);
        return Optional.ofNullable(userMapper.selectOne(wrapper))
                .orElseThrow(() -> new UsernameNotFoundException("用户ID:" + id + "不存在"));
    }

    private void repeatUserUpdate(UserDto userDto) {
        User user = Optional.ofNullable(userMapper.selectById(userDto.getId()))
                .orElseThrow(() -> new ValidationException("非法操作~"));
        if (StringUtils.equals(user.getUsername(), userDto.getUsername())) {
            return;
        }
        QueryWrapper<User> wrapper = new QueryWrapper<User>()
                .eq("username", userDto.getUsername())
                .ne("id", userDto.getId());
        if (userMapper.selectCount(wrapper) > 0) {
            throw new ValidationException("用户名重复~不能用这个用户名来注册啦~");
        }
    }

    private void repeatUser(UserDto userDto) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("username", userDto.getUsername());
        if (userMapper.selectCount(wrapper) > 0) {
            throw new ValidationException("用户名重复~不能用这个用户名来注册啦~");
        }
    }
}
